﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;

using AST.Model;
using AST.DAL;
using AST.Dapper;
using AST.Common;

namespace AST.BLL
{
    public class AdminLogHelper
    {
        public static bool AddLog(string username, string message)
        {
            try
            {
                var param = new DynamicParameters();
                param.Add("@UserName", username);
                param.Add("@Content", message);
                param.Add("@UserIP", "");

                string sql = "insert tblAdminLog(LogId,UserName,LogDate,Content,UserIP) values(UUID(),@UserName,CURRENT_TIMESTAMP(),@Content,@UserIP)";

                DBHelper.ExcuteSQL(sql, param);
            }
            catch (Exception ex)
            {
                Logging.Logging.RecordError(ex);
                return false;
            }
            return true;
        }

        public static AdminLogListEntity GetPagingList(int currentPage, int pageSize, string username)
        {
            AdminLogListEntity objList = new AdminLogListEntity();
            try
            {
                string sbtotalnum = "select count(1) from tblAdminLog where 1=1 ";
                if (!string.IsNullOrEmpty(username))
                {
                    sbtotalnum = sbtotalnum + "and UserName  like @UserName ";
                }

                var param = new DynamicParameters();
                param.Add("@UserName", "%" + username + "%");

                objList.TotCount = DBHelper.ExecuteScalar(sbtotalnum.ToString(), param);
                if (objList.TotCount > 0)
                {
                    var param2 = new DynamicParameters();
                    param2.Add("@FullName", "%" + username + "%");

                    StringBuilder sbdatalist = new StringBuilder();
                    sbdatalist.Append("select * from tblAdminLog where 1=1 ");
                    if (!string.IsNullOrEmpty(username))
                    {
                        sbdatalist.Append("and UserName  like @UserName ");
                    }
                    sbdatalist.Append(string.Format("ORDER BY LogDate DESC LIMIT {0},{1}", ((currentPage - 1) * pageSize).ToString(), pageSize.ToString()));

                    objList.ItemList = DBHelper.ReadCollection<AdminLogEntity>(sbdatalist.ToString(), param2);
                }
            }
            catch (Exception ex)
            {
                Logging.Logging.RecordError(ex);
            }
            if (objList.ItemList == null)
                objList.ItemList = new List<AdminLogEntity>();
            return objList;
        }
    }
}
